package com.common.app.widget.calendarPickerView

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.viewpager2.widget.ViewPager2
import com.common.app.data.bean.CalendarDay
import com.common.app.data.bean.CalendarMonth
import com.common.app.databinding.CalendarPickerLayoutBinding
import java.text.SimpleDateFormat
import java.util.*

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：17/7/2025
 *
 * 描述：日历选择器主控件
 *
 * 修订历史：
 *
 */
class CalendarPickerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    private val binding: CalendarPickerLayoutBinding
    private lateinit var monthAdapter: CalendarMonthAdapter
    private val months = mutableListOf<CalendarMonth>()

    private var currentPosition = 0
    private var limitYears = 1 // 默认限制1年
    private var selectedDay: CalendarDay? = null
    private var onDateSelectedListener: ((CalendarDay) -> Unit)? = null

    private val today = Calendar.getInstance()
    private val currentYear = today.get(Calendar.YEAR)
    private val currentMonth = today.get(Calendar.MONTH)
    private val hasEventDayList = mutableListOf<String>()

    init {
        binding = CalendarPickerLayoutBinding.inflate(LayoutInflater.from(context), this, true)
        setupViews()
        initializeCalendar()
    }

    private fun setupViews() {
        // 设置星期标题
        setupWeekHeaders()

        // 设置ViewPager2
        monthAdapter = CalendarMonthAdapter(months) { day ->
            selectDay(day)
        }

        binding.viewPager.adapter = monthAdapter
        binding.viewPager.orientation = ViewPager2.ORIENTATION_HORIZONTAL

        // 设置ViewPager2回调
        binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                currentPosition = position
                updateMonthTitle()
            }
        })

        // 设置左右箭头点击事件
        binding.btnPrevMonth.setOnClickListener {
            if (currentPosition > 0) {
                binding.viewPager.currentItem = currentPosition - 1
            }
        }

        binding.btnNextMonth.setOnClickListener {
            // 限制不能切换到未来月份
            val currentMonthPosition = getCurrentMonthPosition()
            if (currentPosition < months.size - 1 && currentPosition < currentMonthPosition) {
                binding.viewPager.currentItem = currentPosition + 1
            }
        }
    }

    private fun setupWeekHeaders() {
        val weekDays = arrayOf("一", "二", "三", "四", "五", "六", "日")
        // 这里可以添加星期标题的设置逻辑
    }

    private fun initializeCalendar() {
        months.clear()

        // 计算开始月份（限制年份前的月份）
        val startCalendar = Calendar.getInstance().apply {
            set(currentYear - limitYears, 0, 1)
        }

        // 计算结束月份（只到当前月份，不包含未来月份）
        val endCalendar = Calendar.getInstance().apply {
            set(currentYear, currentMonth, 1)
        }

        val calendar = startCalendar.clone() as Calendar
        var position = 0

        while (calendar.before(endCalendar) || calendar.equals(endCalendar)) {
            val year = calendar.get(Calendar.YEAR)
            val month = calendar.get(Calendar.MONTH)

            months.add(CalendarMonth.create(year, month))

            // 记录当前月份的位置
            if (year == currentYear && month == currentMonth) {
                currentPosition = position
            }

            calendar.add(Calendar.MONTH, 1)
            position++
        }

        monthAdapter.updateMonths(months)

        // 设置到当前月份
        binding.viewPager.setCurrentItem(currentPosition, false)
        updateMonthTitle()
    }

    private fun updateMonthTitle() {
        if (currentPosition < months.size) {
            val month = months[currentPosition]
            val calendar = Calendar.getInstance().apply {
                set(month.year, month.month, 1)
            }

            val monthName = String.format("%d年%d月", month.year, month.month + 1)
            binding.tvMonthTitle.text = monthName

            // 更新箭头状态
            binding.btnPrevMonth.isEnabled = currentPosition > 0

            // 获取当前月份位置
            val currentMonthPosition = getCurrentMonthPosition()

            // 如果当前显示的是当前月份，则隐藏右箭头
            if (currentPosition >= currentMonthPosition) {
                binding.btnNextMonth.visibility = View.GONE
            } else {
                binding.btnNextMonth.visibility = View.VISIBLE
                binding.btnNextMonth.isEnabled = currentPosition < months.size - 1
            }
        }
    }

    /**
     * 获取当前月份在列表中的位置
     */
    private fun getCurrentMonthPosition(): Int {
        return months.indexOfFirst {
            it.year == currentYear && it.month == currentMonth
        }
    }

    private fun selectDay(day: CalendarDay) {
        selectedDay = day
        monthAdapter.setSelectedDay(day)
        onDateSelectedListener?.invoke(day)
    }

    /**
     * 设置年限限制
     */
    fun setLimitYears(years: Int) {
        limitYears = years
        initializeCalendar()
    }

    /**
     * 设置日期选择监听器
     */
    fun setOnDateSelectedListener(listener: (CalendarDay) -> Unit) {
        onDateSelectedListener = listener
    }

    /**
     * 获取当前选中的日期
     */
    fun getSelectedDay(): CalendarDay? = selectedDay

    /**
     * 设置选中日期
     */
    fun setSelectedDay(day: CalendarDay) {
        selectedDay = day
        monthAdapter.setSelectedDay(day)

        // 跳转到对应月份
        val targetPosition = months.indexOfFirst {
            it.year == day.year && it.month == day.month
        }
        if (targetPosition >= 0) {
            binding.viewPager.setCurrentItem(targetPosition, true)
        }
    }

    /**
     * 设置选中日期
     */
    fun setSelectedDayByCalendarDay(day: CalendarDay) {
        // 找到对应月份在列表中的位置
        val targetPosition = months.indexOfFirst {
            it.year == day.year && it.month ==  day.month
        }

        if (targetPosition >= 0) {
            // 跳转到对应月份
            binding.viewPager.setCurrentItem(targetPosition, true)

            // 从对应月份的数据中找到具体的日期对象
            val targetMonthData = months[targetPosition]
            val targetCalendarDay = targetMonthData.days.find {
                it.year ==  day.year && it.month ==  day.month && it.day ==  day.day && it.isCurrentMonth
            }

            // 选中该日期
            targetCalendarDay?.let {targetCalendarDayIt->
                selectedDay = targetCalendarDayIt
                monthAdapter.setSelectedDay(targetCalendarDayIt)
            }
        }
    }

    /**
     * 设置选中日期
     */
    fun setSelectedDayByCalendar(calendar: Calendar) {
        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        // 找到对应月份在列表中的位置
        val targetPosition = months.indexOfFirst {
            it.year == year && it.month == month
        }

        if (targetPosition >= 0) {
            // 跳转到对应月份
            binding.viewPager.setCurrentItem(targetPosition, true)

            // 从对应月份的数据中找到具体的日期对象
            val targetMonthData = months[targetPosition]
            val targetCalendarDay = targetMonthData.days.find {
                it.year == year && it.month == month && it.day == day && it.isCurrentMonth
            }

            // 选中该日期
            targetCalendarDay?.let {targetCalendarDayIt->
                selectedDay = targetCalendarDayIt
                monthAdapter.setSelectedDay(targetCalendarDayIt)
            }
        }
    }

    /**
     * 更新所有月份中的事件日期
     */
    private fun updateEventDays() {
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())

        months.forEach { month ->
            month.days.forEach { day ->
                if (day.isCurrentMonth) {
                    val calendar = Calendar.getInstance().apply {
                        set(day.year, day.month, day.day)
                    }
                    val dateString = dateFormat.format(calendar.time)

                    // 使用反射或者重新创建CalendarDay对象来更新hasEvent属性
                    // 由于CalendarDay的hasEvent是val，我们需要重新创建对象
                    val updatedDay = CalendarDay(
                        year = day.year,
                        month = day.month,
                        day = day.day,
//                        isCurrentMonth = day.isCurrentMonth,
                        isToday = day.isToday,
                        isSelected = day.isSelected,
                        hasEvent = hasEventDayList.contains(dateString),
                        dateName = day.dateName,
                        mCalendar = day.mCalendar
                    )

                    // 替换原来的day对象
                    val dayIndex = month.days.indexOf(day)
                    if (dayIndex >= 0) {
                        (month.days as MutableList)[dayIndex] = updatedDay
                    }
                }
            }
        }

        // 通知适配器数据已更改
        monthAdapter.notifyDataSetChanged()
    }

    /**
     * 设置选中日期
     */
    fun getSelectedDayByCalendar(calendar: Calendar):CalendarDay? {
        // 添加日期格式日志输出
        val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        val formattedDate = dateFormat.format(calendar.time)
        Log.d("CalendarPickerView", "getSelectedDayByCalendar - 输入日期: $formattedDate")

        val year = calendar.get(Calendar.YEAR)
        val month = calendar.get(Calendar.MONTH)
        val day = calendar.get(Calendar.DAY_OF_MONTH)

        Log.d("CalendarPickerView", "getSelectedDayByCalendar - 解析后: 年=$year, 月=${month}, 日=$day")

        // 找到对应月份在列表中的位置
        val targetPosition = months.indexOfFirst {
            it.year == year && it.month == month
        }

        if (targetPosition >= 0) {
            // 从对应月份的数据中找到具体的日期对象
            val targetMonthData = months[targetPosition]
            val targetCalendarDay = targetMonthData.days.find {
                it.year == year && it.month == month && it.day == day && it.isCurrentMonth
            }
            targetCalendarDay?.isSelected = true
            return targetCalendarDay
        }
        return null
    }

    /**
     * 跳转到当前月份并选中今天的日期
     */
    fun goToToday() {
        // 获取今天的日期
        val todayCalendar = Calendar.getInstance()
        val todayYear = todayCalendar.get(Calendar.YEAR)
        val todayMonth = todayCalendar.get(Calendar.MONTH)
        val todayDay = todayCalendar.get(Calendar.DAY_OF_MONTH)

        // 找到当前月份在列表中的位置
        val currentMonthPosition = months.indexOfFirst {
            it.year == todayYear && it.month == todayMonth
        }

        if (currentMonthPosition >= 0) {
//            // 跳转到当前月份
//            binding.viewPager.setCurrentItem(currentMonthPosition, true)

            // 从当前月份的数据中找到今天的日期对象
            val currentMonthData = months[currentMonthPosition]
            val todayCalendarDay = currentMonthData.days.find {
                it.year == todayYear && it.month == todayMonth && it.day == todayDay && it.isCurrentMonth
            }

            // 选中今天的日期
            todayCalendarDay?.let {
                selectDay(it)
            }
        }
    }

    /**
     * 重置到当前月份（不选中日期）
     */
    fun resetToCurrentMonth() {
        val currentMonthPosition = getCurrentMonthPosition()
        if (currentMonthPosition >= 0) {
            binding.viewPager.setCurrentItem(currentMonthPosition, true)
        }
    }

    /**
     * 设置有事件的日期列表
     */
    fun setHasEventDayList(eventDays: List<String>) {
        hasEventDayList.clear()
        hasEventDayList.addAll(eventDays)
        updateEventDays()
    }

    /**
     * 添加事件的日期
     */
    fun addEventDay(dateString: String) {
        if (!hasEventDayList.contains(dateString)) {
            hasEventDayList.add(dateString)
            updateEventDays()
        }
    }

    /**
     * 移除对应事件的日期
     */
    fun removeEventDay(dateString: String) {
        if (hasEventDayList.remove(dateString)) {
            updateEventDays()
        }
    }

    fun setShowGreyPoint(show:Boolean){
        monthAdapter.setShowGreyPoint(show)
    }
}